package com.miya.lib_common.networking;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpsTrustTool implements X509TrustManager {

    private static HttpsTrustTool instance;

    public static HttpsTrustTool getInstance() {
        return instance;
    }

    static {
        instance = new HttpsTrustTool();
    }

    private TrustManager[] trustManagers;

    private final X509Certificate[] x509Certificates = new X509Certificate[]{};

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return x509Certificates;
    }

    public void trustAll() {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        SSLContext context;
        if (instance.trustManagers == null) {
            instance.trustManagers = new TrustManager[]{new HttpsTrustTool()};
        }

        try {
            context = SSLContext.getInstance("TLS");
            context.init(null, instance.trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    }
}
